//
//  SubscriptionViewController.m
//  FAKER
//
//  Created by Jianwei on 15/11/2.
//  Copyright © 2015年 YHLai. All rights reserved.
//

#import "SubscriptionViewController.h"
#import "AllHeader.h"
#import "BaseClassCollectionView.h"
#import "WFRepeatImageModel.h"
#import "WFChannelPlateModel.h"
#import "FitHeader.h"
#import "WFChannelPlateCollectionViewCell.h"
#import "WFRepeatImageCollectionViewCell.h"
#import "YHCirculationView.h"
#import "WFChannelDetailViewController.h"
#define REPEAT_DATA_URLSTRING @"http://iphone.myzaker.com/zaker/follow_promote.php?_appid=iphone"
#define CHANNEL_PLATE_URLSTRING @"http://iphone.myzaker.com/zaker/intro_block.php?_appid=iphone&_bsize=750_1334&_dev=iPhone%2C9.1&_lat=0.000000&_lng=0.000000&_mac=02%3A00%3A00%3A00%3A00%3A00&_net=wifi&_udid=F831707A-4E20-4C4F-8DFF-43432BC0305B&_uid=&_utoken=&_v=6.4.1&_version=6.4&type_ids=45%2C62%2C47"
@interface SubscriptionViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UIScrollViewDelegate>
@property(nonatomic, strong)BaseClassCollectionView *plateCollectionView;
//@property(nonatomic, strong)BaseClassCollectionView *imageViewCollectionView;
@property(nonatomic, strong)NSMutableArray *repeatImageDataArray;
@property(nonatomic, strong)UIPageControl *pageControl;
@property(nonatomic, strong)NSArray *coreArray;
@property(nonatomic, strong)NSMutableArray *dataArray;
@property(nonatomic, strong)CoreDataManager *manager;
@end

@implementation SubscriptionViewController
#pragma mark 获取数据
- (void)getRepeatImageData
{
    [InternetDataRequest getDataByString:REPEAT_DATA_URLSTRING BodyDic:nil WithDataBlock:^(id data) {
        NSArray *array = [[data objectForKey:@"data"] objectForKey:@"list"];
        [self createCirculationView:array];
    }];
}
- (void)getChannelPlateData
{
    [InternetDataRequest getDataByString:CHANNEL_PLATE_URLSTRING BodyDic:nil WithDataBlock:^(id data) {
        NSArray *array = [[data objectForKey:@"data"] objectForKey:@"blocksData"];
        for (NSDictionary *dic in array) {
            WFChannelPlateModel *model = [[WFChannelPlateModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            NewChannel *newChannel = [NSEntityDescription insertNewObjectForEntityForName:@"NewChannel" inManagedObjectContext:_manager.managedObjectContext];
            newChannel.title = model.title;
            newChannel.pic = model.pic;
            newChannel.block_color = model.block_color;
            newChannel.api_url = model.api_url;
            [_manager saveContext];
            
        }
        [self getDataFromCoreData];
        [NSUSERDEFAULTS setBool:1 forKey:@"NewChannel"];
    }];
}
- (void)getDataFromCoreData
{
    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"NewChannel"];
    _coreArray = [NSArray arrayWithArray:[_manager.managedObjectContext executeFetchRequest:fetchRequest error:nil]];
    _dataArray = [NSMutableArray arrayWithArray:_coreArray];
    WFChannelPlateModel *model = [[WFChannelPlateModel alloc]init];
    model.title = @"添加更多";
    [_dataArray addObject:model];
    [_plateCollectionView reloadData];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"订阅";
    //    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:18], NSForegroundColorAttributeName:[UIColor whiteColor]}];
    
    //右侧搜索按钮
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-search@2x"] style:UIBarButtonItemStylePlain target:self action:@selector(clickSearchButtonAction)];
}
- (void)loadView
{
    [super loadView];
    //初始化数据数组
    _manager = [CoreDataManager shareManager];
    
    _repeatImageDataArray = [NSMutableArray array];
    
    _coreArray = [NSArray array];
    
    [self getRepeatImageData];
    if ([NSUSERDEFAULTS boolForKey:@"NewChannel"] == 0) {
        [self getChannelPlateData];
    }
    //        [self getDataFromCoreData];
    
    //轮播图CollectionViewFlowLayout以及CollectionView布局
    //    UICollectionViewFlowLayout *imageViewCollectionViewFlowLayout = [[UICollectionViewFlowLayout alloc]init];
    //    imageViewCollectionViewFlowLayout.itemSize = CGSizeMake(SCREEN_WIDTH, 210 * FITHEIGHT);
    //    imageViewCollectionViewFlowLayout.minimumLineSpacing = 0;
    //    imageViewCollectionViewFlowLayout.minimumInteritemSpacing = 0;
    //    imageViewCollectionViewFlowLayout.scrollDirection = 1;
    //
    //    _imageViewCollectionView = [[BaseClassCollectionView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 210 * FITHEIGHT) collectionViewLayout:imageViewCollectionViewFlowLayout];
    //    _imageViewCollectionView.delegate = self;
    //    _imageViewCollectionView.dataSource = self;
    //    _imageViewCollectionView.pagingEnabled = 1;
    ////    _imageViewCollectionView.showsHorizontalScrollIndicator = 0;
    //    [_imageViewCollectionView registerClass:[WFRepeatImageCollectionViewCell class] forCellWithReuseIdentifier:@"imageView"];
    
    
    
    //首页板块CollectionViewFlowLayout以及CollectionView布局
    UICollectionViewFlowLayout *plateCollectionViewFlowLayout = [[UICollectionViewFlowLayout alloc]init];
    plateCollectionViewFlowLayout.itemSize = CGSizeMake((SCREEN_WIDTH - 3) / 3, (SCREEN_WIDTH - 3) / 3);
    plateCollectionViewFlowLayout.minimumInteritemSpacing = 1.5 * FITWIDTH;
    plateCollectionViewFlowLayout.minimumLineSpacing = 1.5 * FITWIDTH;
    plateCollectionViewFlowLayout.sectionInset = UIEdgeInsetsMake(210 * FITHEIGHT, 0, 0, 0);
    
    _plateCollectionView = [[BaseClassCollectionView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, (667 - 64 - 49) * FITHEIGHT) collectionViewLayout:plateCollectionViewFlowLayout];
    _plateCollectionView.delegate = self;
    _plateCollectionView.dataSource = self;
    //    _plateCollectionView.showsVerticalScrollIndicator = 0;
    [_plateCollectionView registerClass:[WFChannelPlateCollectionViewCell class] forCellWithReuseIdentifier:@"plate"];
    [self.view addSubview:_plateCollectionView];
    //    [_plateCollectionView addSubview:_imageViewCollectionView];
    //    _plateCollectionView.backgroundColor = [UIColor colorWithRed:0.94 green:0.94 blue:0.94 alpha:1];
    
    //    [_plateCollectionView reloadData];
    [self getDataFromCoreData];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    //    if (collectionView == _imageViewCollectionView) {
    //        WFRepeatImageCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"imageView" forIndexPath:indexPath];
    //        cell.repeatImageModel = _repeatImageDataArray[indexPath.row];
    //        return cell;
    //    }
    //    else
    //    {
    WFChannelPlateCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"plate" forIndexPath:indexPath];
    cell.channelPlateModel = _dataArray[indexPath.row];
    cell.layer.transform = CATransform3DMakeScale(0.3, 0.3, 0.1);
    [UIView animateWithDuration:0.5 animations:^{
        cell.layer.transform = CATransform3DMakeScale(1, 1, 0.1);
    }];
    
    if (indexPath.row == _dataArray.count - 1)
    {
        cell.picImageView.image = [UIImage imageNamed:@"common_icon_subscribe@3x"];
        cell.picImageView.contentMode = 4;
        cell.picImageView.frame = CGRectMake(17 * FITWIDTH, 7 * FITWIDTH, 90 * FITWIDTH, 90 * FITWIDTH);
        cell.titleLabel.frame = CGRectMake(0, 70 * FITHEIGHT, cell.picImageView.WIDTH, 20 * FITWIDTH);
    }
    else
    {
        cell.picImageView.contentMode = 0;
        cell.picImageView.frame = CGRectMake(17 * FITWIDTH, 17 * FITWIDTH, 90 * FITWIDTH, 90 * FITWIDTH);
        cell.titleLabel.frame = CGRectMake(0, 60  * FITHEIGHT, cell.picImageView.WIDTH, 20 * FITWIDTH);
    }
    return cell;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _dataArray.count;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView == _plateCollectionView) {
        if (indexPath.row == _dataArray.count - 1)
        {
            [self clickSearchButtonAction];
        }
        else
        {
            WFChannelDetailViewController *wc = [[WFChannelDetailViewController alloc]init];
            wc.api_url = [_dataArray[indexPath.row] api_url];
            [wc setHidesBottomBarWhenPushed:1];
            [self.navigationController pushViewController:wc animated:1];
        }
    }
}
//- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
//{
//    if (scrollView == _imageViewCollectionView) {
//        _pageControl.currentPage = scrollView.contentOffset.x / scrollView.WIDTH;
//    }
//}
- (void)createCirculationView:(NSArray *)array
{
    YHCirculationView *circulationView = [[YHCirculationView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 210 * FITHEIGHT) ImageDictArray:array];
    [self.view addSubview:circulationView];
    [_plateCollectionView addSubview:circulationView];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
//- (void)createPageControl:(NSInteger)numbers
//{
//    _pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake(0, 200, 50, 10)];
//    _pageControl.numberOfPages = numbers;
//    _pageControl.center = CGPointMake(SCREEN_WIDTH / 2, 205);
//    [self.view addSubview:_pageControl];
//}
- (void)pushSearchViewController
{
    WFChannelViewController *wc = [[WFChannelViewController alloc]init];
    [self.navigationController pushViewController:wc animated:1];
}
#pragma mark - 点击搜索按钮方法
- (void)clickSearchButtonAction
{
    WFChannelViewController *wc = [[WFChannelViewController alloc]init];
    [wc setHidesBottomBarWhenPushed:1];
    [self.navigationController pushViewController:wc animated:1];
}

- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.hidden = 0;
    //    NSLog(@"%@", [_manager applicationDocumentsDirectory]);
    //    if ([NSUSERDEFAULTS boolForKey:@"ADD"] == 1) {
    //        [self getDataFromCoreData];
    //        [NSUSERDEFAULTS setBool:0 forKey:@"ADD"];
    //    }
    [self getDataFromCoreData];
    
}
- (void)viewWillDisappear:(BOOL)animated
{
    [_dataArray removeObjectAtIndex:[_dataArray count] - 1];
}

@end
